package cn.kgc.ssmmodulardemo.controller;

import cn.kgc.ssmmodulardemo.entity.User;
import cn.kgc.ssmmodulardemo.entity.vo.addUserVO;
import cn.kgc.ssmmodulardemo.service.UserService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Api(description = "用户管理")
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "用户登录",produces = "appliction/josn",notes = "状态码:10000登录成功,10001:用户名或密码不正确")
    @RequestMapping(value = "/login",method= RequestMethod.POST,produces = "appliction/json")
    @ResponseBody
    public Object userLogin(@RequestParam("userCode")String userCode,
                            @RequestParam("userPassword")String userPassword, HttpSession httpSession){
        JSONObject josnObject=new JSONObject();

        String data="";

        String message="";

        String statCode="";

        User user=new User();
        user.setUserCode(userCode);
        user.setUserPassword(userPassword);
        User result=userService.UserLogin(user);
        if (result!=null){
            data=result.toString();
            message="登陆成功";
            statCode="10001";
        }else {
            data="";
            message="用户名或密码错误";
            statCode="10001";
        }
        josnObject.put("data",data);
        josnObject.put("message",message);
        josnObject.put("statCode",statCode);

        return josnObject.toString();
    }

    /**
     * Valid 用来帮助我们校验数据的合法性
     * @param addUserVO 视图对象，要求该对象的属性内容必须要和前端传过来的值一模一样
     * @param result 用来返回对象是否合法性
     * @return 返回视图模型 如果合法返回到succes 页面 否则跳转到error
     */
    @ApiOperation(value = "用户添加类",produces = "application/json")
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public ModelAndView testAdd(@RequestBody addUserVO addUserVO, BindingResult result){
            ModelAndView modelAndView=new ModelAndView();
        if (result.hasErrors()){
            System.out.println("检测到数据的不合法性");
            System.out.println(result.getFieldErrors().toString());
            modelAndView.setViewName("error");
        }else {
            modelAndView.setViewName("success");
        }
        return modelAndView;
    }
}
